package com.finance.controller;

import com.finance.domain.User;
import com.finance.utils.GravatarUtil;
import com.finance.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController extends BaseController {


    /**
     * 跳转dashboard.html后台首页
     *
     * @param model
     * @return
     */
    @RequestMapping("/admin")
    public String toDashboard(Model model) {
        return "dashboard";
    }

    /**
     * 首页跳转Login页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/login/{role}")
    public String toLogin(@PathVariable String role, Model model) {
        model.addAttribute("role", role);
        return "login";
    }

    /**
     * 跳转Register页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String toRegister(Model model) {
        return "register";
    }

    /**
     * 重置密码页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/reset")
    public String reset(Model model) {
        return "reset";
    }


    /**
     * 修改密码页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/configuration")
    public String configuration(Model model) {
        return "configuration";
    }


    /**
     * 注销跳转登录
     *
     * @return
     */
    @RequestMapping("/logout")
    public String toLogout(Model model) {
        session.invalidate();
        return "redirect:/login/user";
    }

    /**
     * 通过ajax重置密码
     *
     * @param u
     * @return
     */
    @RequestMapping("/userReset")
    @ResponseBody
    public Map<String, Object> userReset(User u) {
        Map<String, Object> map = new HashMap<>();

        User userByUserName = userService.findUserByUserName(u.getName());
        if (null == userByUserName || !u.getMail().equals(userByUserName.getMail())) {
            map.put("data", "error");
        }else{
            userByUserName.setPassword(StringUtil.passwordToMd5("123456"));
            userService.updateByPrimaryKey(userByUserName);
            map.put("data", "success");
        }


        return map;
    }

    /**
     * 通过ajax登录系统后台
     *
     * @param u
     * @param remember
     * @return
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public Map<String, Object> userLogin(User u,
                                         @RequestParam(value = "remember", required = false) String remember,
                                         HttpServletRequest req, HttpServletResponse resp) {
        Map<String, Object> map = new HashMap<>();


        User userByUserName = userService.findUserByUserName(u.getName());
        //账号不存在或者角色不匹配
        if (null == userByUserName || !u.getRole().equals(userByUserName.getRole())) {
            map.put("data", u.getRole() + "NoExist");
            return map;
        }

        User user = userService.selectUserByNameAndPassword(u);
        if (user == null) {
            //密码不正确
            map.put("data", u.getRole() + "Error");
        } else {
            map.put("data", "success");
            session.setAttribute("USER_SESSION", user);
            session.setAttribute("USER_ID", user.getUid());
            if ("on".equals(remember)) {
                Cookie cookie = new Cookie("JSESSIONID", req.getSession().getId());
                cookie.setMaxAge(60 * 60 * 24 * 7);
                session.setMaxInactiveInterval(60 * 60 * 24 * 7);
                resp.addCookie(cookie);
            }
        }
        return map;
    }

    /**
     * 通过ajax注册
     *
     * @param u
     * @return
     */
    @RequestMapping("/userRegister")
    @ResponseBody
    public Map<String, Object> userRegister(User u) {
        User user = u;
        Map<String, Object> map = new HashMap<>();
        String pwd = u.getPassword();
        user.setPassword(StringUtil.passwordToMd5(pwd));
        user.setCreated(new Date());
        user.setActivated(new Date());
        if(StringUtils.isEmpty(u.getRole())){
            user.setRole("user");
        }
        user.setCreateBy(String.valueOf(session.getAttribute("USER_ID")));
        user.setPhoto(GravatarUtil.getGravatarUrlByEmail(u.getMail()));
        int value = userService.insert(u);
        if (value == 0) {
            map.put("data", "error");
        } else {
            map.put("data", "success");
        }
        return map;
    }

    /**
     * userUpdate
     *
     * @param u
     * @return
     */
    @RequestMapping("/userUpdate")
    @ResponseBody
    public Map<String, Object> userUpdate(User u) {
        User user = u;
        Map<String, Object> map = new HashMap<>();
        String pwd = u.getPassword();
        user.setPassword(StringUtil.passwordToMd5(pwd));
        user.setActivated(new Date());
        user.setRole("user");
        user.setPhoto(GravatarUtil.getGravatarUrlByEmail(u.getMail()));
        int value = userService.updateByPrimaryKey(u);
        if (value == 0) {
            map.put("data", "error");
        } else {
            map.put("data", "success");
        }
        return map;
    }

    /**
     * 通过用户名查找用户
     *
     * @param userName
     * @return
     */
    @RequestMapping("/findUserByUserName")
    @ResponseBody
    public Map<String, Object> findUserByUserName(@RequestParam(value = "userName") String userName) {
        Map<String, Object> map = new HashMap<>();
        User user = userService.findUserByUserName(userName);
        boolean userExist = false;
        if (user != null) {
            userExist = true;
        }
        map.put("userExist", userExist);
        return map;
    }



    @RequestMapping("/updateUserPassword")
    @ResponseBody
    public Map<String, Object> updateUserPassword(String oldPwd, String newPwd) {
        Map<String, Object> map = new HashMap<>();
        String newOldPwd = StringUtil.passwordToMd5(oldPwd);
        User u = (User) session.getAttribute("USER_SESSION");
        if (u.getPassword().equals(newOldPwd)) {
            u.setPassword(StringUtil.passwordToMd5(newPwd));
            int a = userService.updatePassword(u);
            if (a == 1) {
                map.put("data", "success");
            } else {
                map.put("data", "fail");
            }
        } else {
            map.put("data", "pwdfail");
        }
        return map;
    }

    @RequestMapping("/deleteUser/{uid}")
    public String deleteUser(@PathVariable int uid) {
        int a = userService.deleteByPrimaryKey(uid);
        return "redirect:/adminUser";
    }

    /**
     * 跳转user-mgr.html页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/adminUser")
    public String adminUser(Model model) {
        return "user-mgr";
    }


    /**
     * 获取用户列表
     *
     * @return
     */
    @RequestMapping("/adminGetUserList")
    @ResponseBody
    public Map<String, Object> adminGetUserList() {
        Map<String, Object> map = new HashMap<>();
        String user_id = String.valueOf(session.getAttribute("USER_ID"));
        List<User> users = userService.selectAllUser(user_id);
        map.put("data", users);
        return map;
    }
}
